<template>
  <div class="QR">
    <h4>请输入要生成的内容:</h4>
    <div class="inputContent">
      <el-input v-model="data.payContent" placeholder="请输入内容"/>
      <button class="qrBtn" @click="handleQrcode">生成二维码</button>
    </div>
    
    <div v-if="data.payUrl" class="Qcode" ref="canvasRefCode">
      <qrcode-vue :value="data.payUrl" :size="data.size" level="Q" />
    </div>
    <button style="margin-left:150px" v-if="data.payUrl" class="qrBtn" @click="saveQRcode">保存二维码</button>
    <h4>请选择要识别的二维码图片:</h4>
    <Explain/>
  </div>
</template>
<script setup>
import html2canvas  from 'html2canvas'
import Explain from './ExplainQRcode.vue'
import {nextTick, onMounted, reactive, ref} from "vue";
import QrcodeVue from 'qrcode.vue'
import {debounce} from "../../toolsjs/debounce";
const canvasRefCode = ref()
const data = reactive({
  size:200,
  payContent:'',
  payUrl:'',
})
const handleQrcode = debounce(()=>{
    if(data.payContent != ''){
      nextTick(()=>{
        data.payUrl = data.payContent
        
      })
    }else{
      ElMessage({
        showClose: true,
        message: '生成二维码的内容不能为空！！',
        type: "warning",
      })
    }
},500)
const saveQRcode = ()=>{
  html2canvas(canvasRefCode.value,{backgroundColor:null,useCORS:true}).then((canvas)=>{
    let url =  canvas.toDataURL('image/png')
    let aLink = document.createElement('a')
    aLink.style.display = 'none'
    aLink.href = url;
    aLink.download = new Date().toLocaleString();
    // 创建一个点击事件并对 a 标签进行触发
    const event = new MouseEvent('click');
    aLink.dispatchEvent(event);
  })
}

</script>
<style lang="less" scoped>
h4{
  padding: 10px 0;
}
.QR{
  margin: 0 auto;
  width: min(90%,400px);
  display: flex;
  flex-flow: column;
  justify-content: center;
  .inputContent{
    display: flex;
    /deep/ .el-button{
      margin-left: 10px !important;
    }
  }
}
  .Qcode{
    border:1px solid #fff;
    margin: 20px auto;
  }
  /deep/ .el-input__wrapper.is-focus{
    box-shadow: 0 0 0 1px #161616 inset;
  }
.qrBtn {
  width: 6.5rem;
  height: 35px;
  border-radius: 5px;
  margin-left: 10px;
  z-index: 1;
  position: relative;
  font-size: 13px;
  font-family: inherit;
  color: white;
  padding: 0.3em .5em;
  outline: none;
  border: none;
  background-color: hsl(236, 32%, 26%);
  overflow: hidden;
  transition: color 0.4s ease-in-out;

}

.qrBtn::before {
  content: '';
  z-index: -1;
  position: absolute;
  top: 50%;
  left: 50%;
  width: 1em;
  height: 1em;
  border-radius: 50%;
  background-color: #3cefff;
  transform-origin: center;
  transform: translate3d(-50%, -50%, 0) scale3d(0, 0, 0);
  transition: transform 0.45s ease-in-out;
}

.qrBtn:hover {
  cursor: pointer;
  color: #161616;
}

.qrBtn:hover::before {
  transform: translate3d(-50%, -50%, 0) scale3d(15, 15, 15);
}

</style>